package com.ck.company.controller.client;

import com.ck.annotation.PermissionRequired;
import com.ck.company.service.CpProgramPutinService;
import com.ck.constant.ProgramPutinConstant;
import com.ck.constant.ResponseConstant;
import com.ck.exception.ServiceException;
import com.ck.model.common.ProgramPutin;
import com.ck.model.common.sys.JsonResponse;
import com.ck.util.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;

/**
 * 客户端-节目投放
 *
 * @author linqiang
 * @date 2018-09-30 14:40
 */
@PermissionRequired
@Controller
@RequestMapping(value = "/client/program/putin")
public class CpProgramPutinClientController {
    private Logger logger = LoggerFactory.getLogger(CpProgramPutinClientController.class);
    @Autowired
    private CpProgramPutinService cpProgramPutinService;

    /**
     * 新增节目投放设置（终端分组和终端机器码只能选择一种）
     *
     * @param programId          节目ID
     * @param putinLevel         投放级别（1普通计划，2插播计划）
     * @param startTime          节目投放开始时间
     * @param endTime            节目投放结束时间
     * @param putinDeviceGroupId 投放分组ID(多个英文逗号隔开)
     * @param putinDeviceCodes   投放终端code(多个英文逗号隔开)
     * @param request            请求
     * @return JsonResponse
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public Object save(Long programId, Integer putinLevel, String startTime, String endTime, String putinDeviceGroupId,
                       String putinDeviceCodes, HttpServletRequest request) {
        JsonResponse checkResult = this.checkPutinParam(0, programId, null, putinLevel, startTime,
                endTime, putinDeviceGroupId, putinDeviceCodes);
        if (null != checkResult) {
            return checkResult;
        }
        try {
            Long[] longTimeArr = this.getLongTimeFromStrTime(startTime, endTime);
            Long startTimeL = longTimeArr[0];
            Long endTimeL = longTimeArr[1];
            if (putinLevel == ProgramPutinConstant.LEVEL_COMMON) {
                JsonResponse checkTimeResult = this.checkPutinTime(startTimeL, endTimeL);
                if (null != checkTimeResult) {
                    return checkTimeResult;
                }
            }
            ProgramPutin programPutin = null;
            if (StringUtils.isNotBlank(putinDeviceGroupId)) {
                programPutin = cpProgramPutinService.putinByDeviceGroup(programId, putinLevel, startTimeL, endTimeL
                        , putinDeviceGroupId, null, request);
            } else if (StringUtils.isNotBlank(putinDeviceCodes)) {
                programPutin = cpProgramPutinService.putinByDeviceCode(programId, putinLevel, startTimeL, endTimeL
                        , putinDeviceCodes, request);
            }
            if (null != programPutin) {
                return new JsonResponse(ResponseConstant.CODE_SUCCESS, programPutin, ProgramPutinConstant.MSG_PUTIN_SUCCESS);
            }
        } catch (ServiceException e) {
            logger.error("CpProgramPutinClientController save fail: " + e.getMessage());
            return new JsonResponse(ResponseConstant.CODE_FAIL, e.getMessage());
        } catch (Exception e) {
            logger.error("CpProgramPutinClientController save fail: " + e.getMessage());
        }
        return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramPutinConstant.MSG_PUTIN_FAIL);
    }


    /**
     * 更新节目投放设置（终端分组和终端机器码只能选择一种）
     *
     * @param programPutinId     id
     * @param putinLevel         投放级别（1普通计划，2插播计划）
     * @param startTime          节目投放开始时间
     * @param endTime            节目投放结束时间
     * @param putinDeviceGroupId 投放分组ID(多个英文逗号隔开)
     * @param putinDeviceCodes   投放终端code(多个英文逗号隔开)
     * @param request            请求
     * @return JsonResponse
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(Long programPutinId, Integer putinLevel, String startTime, String endTime, String putinDeviceGroupId,
                         String putinDeviceCodes, HttpServletRequest request) {
        JsonResponse checkResult = this.checkPutinParam(1, null, programPutinId, putinLevel, startTime,
                endTime, putinDeviceGroupId, putinDeviceCodes);
        if (null != checkResult) {
            return checkResult;
        }
        try {
            Long[] longTimeArr = this.getLongTimeFromStrTime(startTime, endTime);
            Long startTimeL = longTimeArr[0];
            Long endTimeL = longTimeArr[1];
            if (putinLevel == ProgramPutinConstant.LEVEL_COMMON) {
                JsonResponse checkTimeResult = this.checkPutinTime(startTimeL, endTimeL);
                if (null != checkTimeResult) {
                    return checkTimeResult;
                }
            }
            int row = 0;
            if (StringUtils.isNotBlank(putinDeviceGroupId)) {
                row = cpProgramPutinService.updatePutinByDeviceGroup(programPutinId, putinLevel, startTimeL, endTimeL
                        , putinDeviceGroupId, null, request);
            } else if (StringUtils.isNotBlank(putinDeviceCodes)) {
                row = cpProgramPutinService.updatePutinByDeviceCode(programPutinId, putinLevel, startTimeL, endTimeL
                        , putinDeviceCodes, request);
            }
            if (row > 0) {
                return new JsonResponse(ResponseConstant.CODE_SUCCESS, ProgramPutinConstant.MSG_PUTIN_UPDATE_SUCCESS);
            }
        } catch (Exception e) {
            logger.error("CpProgramPutinClientController update fail: " + e.getMessage());
        }
        return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramPutinConstant.MSG_PUTIN_UPDATE_FAIL);
    }

    /**
     * 检查节目投放参数
     *
     * @param optType            操作类型（0添加， 1修改）
     * @param programPutinId     节目投放ID
     * @param programId          节目ID
     * @param putinLevel         投放级别
     * @param startTime          投放开始时间
     * @param endTime            投放结束时间
     * @param putinDeviceGroupId 投放分组ID(多个英文逗号隔开)
     * @param putinDeviceCodes   投放终端code(多个英文逗号隔开)
     * @return
     */
    private JsonResponse checkPutinParam(Integer optType, Long programId, Long programPutinId, Integer putinLevel, String startTime, String endTime, String putinDeviceGroupId,
                                         String putinDeviceCodes) {
        if (optType == 0 && programId == null) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramPutinConstant.MSG_PROGRAM_ID_NOT_NULL);
        }
        if (optType == 1 && programPutinId == null) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramPutinConstant.MSG_PROGRAM_PUTIN_ID_NOT_NULL);
        }
        if (null == putinLevel) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramPutinConstant.MSG_PUTIN_LEVEL_NOT_NULL);
        }
        if (putinLevel == ProgramPutinConstant.LEVEL_INSERTING) {
            //插播节目开始时间必须为无限制，结束时间不能为无限制
            if (StringUtils.isNotBlank(startTime)) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramPutinConstant.MSG_PUTIN_START_TIME_MUST_NULL);
            }
            if (StringUtils.isBlank(endTime)) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramPutinConstant.MSG_PUTIN_END_TIME_NOT_NULL);
            }
        }
        if (StringUtils.isBlank(putinDeviceGroupId) && StringUtils.isBlank(putinDeviceCodes)) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramPutinConstant.MSG_PUTIN_DEVICE_OR_DEVICE_GROUP_NOT_NULL);
        }
        return null;
    }

    /**
     * 根据字符串时间获取Long时间
     *
     * @param startTime 投放开始时间
     * @param endTime   投放结束时间
     * @return Long[](两位的数组, 第一位为开始时间, 第二位为结束时间)
     * @throws ParseException
     */
    private Long[] getLongTimeFromStrTime(String startTime, String endTime) {
        Long startTimeL = null;
        Long endTimeL = null;
        try {
            if (StringUtils.isNotBlank(startTime)) {
                startTimeL = DateUtils.stringTimeToLongTimeStamp(startTime, DateUtils.PATTEN_YMD_HMS1);
            } else {
                startTimeL = ProgramPutinConstant.UNLIMIT_START_TIME;
            }
            if (StringUtils.isNotBlank(endTime)) {
                endTimeL = DateUtils.stringTimeToLongTimeStamp(endTime, DateUtils.PATTEN_YMD_HMS1);
            } else {
                endTimeL = ProgramPutinConstant.UNLIMIT_END_TIME;
            }
        } catch (Exception e) {
            logger.error("格式化节目投放时间出现异常：" + e.getMessage());
        }
        return new Long[]{startTimeL, endTimeL};
    }

    /**
     * 校验投放时间
     *
     * @param startTimeL 投放开始时间
     * @param endTimeL   投放结束时间
     * @return JsonResponse
     */
    private JsonResponse checkPutinTime(Long startTimeL, Long endTimeL) {
        Long nowTimeL = System.currentTimeMillis();
        if (!endTimeL.equals(ProgramPutinConstant.UNLIMIT_END_TIME) && endTimeL <= nowTimeL) {
            return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramPutinConstant.MSG_PUTIN_END_TIME_MUST_GREATER_THAN_NOW_TIME);
        }
        if (!startTimeL.equals(ProgramPutinConstant.UNLIMIT_START_TIME) && !endTimeL.equals(ProgramPutinConstant.UNLIMIT_END_TIME)) {
            if (startTimeL >= endTimeL) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, ProgramPutinConstant.MSG_PUTIN_END_TIME_MUST_GREATER_THAN_START_TIME);
            }
        }
        return null;
    }
}
